﻿using AutoMapper;
using DFGK.IRepository;
using DFGK.IService;
using DFGK_WMS.Model.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DFGK.Service
{
    public class MaterialGroupService : BaseService, IMaterialGroupService
    {
        private readonly IMaterialGroupRepository _materialGroupRepository;
        private readonly IUnitOfWork _unitOfWork;
        public MaterialGroupService(IMapper mapper, IMaterialGroupRepository _materialGroupRepository, IUnitOfWork unitOfWork) : base(mapper)
        {
            this._materialGroupRepository = _materialGroupRepository;
            _unitOfWork = unitOfWork;
        }

        public bool AddMaterialGroup(MaterialGroup m)
        {
            var mobj = _materialGroupRepository.QueryIsEntityWhere(x => x.Code == m.Code);
            if (mobj != null)
            {
                return false;
            }

            _materialGroupRepository.AddEntity(m);
            return _unitOfWork.SaveChangesEntity();
        }

        public bool DelMaterialGroup(long mid)
        {
            var mobj = _materialGroupRepository.QueryEntityById(mid);
            if (mobj != null)
            {
                _materialGroupRepository.DelEntity(mobj);
            }
            return _unitOfWork.SaveChangesEntity();
        }

        public MaterialGroup? GetMaterialGroupById(long mid)
        {
            return _materialGroupRepository.QueryEntityById(mid);
        }

        public List<MaterialGroup> GetMaterialGroupList(string? manme, int pageIndex, int pageSize, out int totalCount)
        {
            var list = _materialGroupRepository.GetEntityAlls();
            if (!string.IsNullOrEmpty(manme))
            {
                list = list.Where(x => x.Name.Contains(manme));
            }
            var lists = _materialGroupRepository.GetEntityAlls(list, pageIndex, pageSize, out totalCount, x => x.CreateDate, false);
            return lists.ToList();
        }

        public bool UpdMaterialGroup(MaterialGroup m)
        {
            var list = _materialGroupRepository.QueryIsEntityWhere(x => x.Id != m.Id && x.Code == m.Code);

            if (list != null)
            {
                return false;
            }
            _materialGroupRepository.UpdEntity(m);
            return _unitOfWork.SaveChangesEntity();
        }
    }
}
